/**
 *  created by jsq on 2017/11/10
 *  2018/12/20优化代码
 */
import React from 'react';
import {connect} from 'react-redux';
import menuRoute from 'routes/menuRoute';
import config from 'config';
import {messages} from "share/common";
import {Form, Button, Select, Icon, Table, message, Popconfirm} from 'antd';
import ListSelector from 'components/list-selector';
import 'styles/setting/department-group/department-group-detail.scss';
import deptGroupService from 'containers/setting/department-group/dept-group.service';
import ResizeTable from "components/resize-table";

class DepartmentGroupDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      batchDelete: true,
      buttonLoading: false,
      deptListSelector: false,  //控制部门选则弹框
      data: [],
      selectedRowKeys: [],
      selectedEntityOIDs: [],   //已选择的列表项的OIDs
      pagination: {
        current: 1,
        page: 0,
        total: 0,
        pageSize: 10,
      },
      deptSelectorItem: {
        title: messages('setting.key480'/*部门*/),
        url: `${config.baseUrl}/api/DepartmentGroup/selectDepartmentByGroupCodeAndDescription`,
        searchForm: [
          {
            type: 'input',
            id: 'deptGroupCode',
            label: messages('components.key63'/*部门编码*/),
            defaultValue: ''
          },
          {
            type: 'input',
            id: 'name', label: messages('setting.key482'/*部门名称*/),
            defaultValue: ''
          },
        ],
        columns: [
          {
            title: messages('components.key63'/*部门编码*/),
            dataIndex: 'custDeptNumber'
          },
          {
            title: messages('setting.key482'/*部门名称*/),
            dataIndex: 'name'
          }
        ],
        key: 'departmentId'
      },
      columns: [
        {
          title: messages('components.key63'/*部门编码*/),
          key: 'custDeptNumber',
          dataIndex: 'custDeptNumber'
        },
        {
          title: messages('setting.key482'/*部门名称*/),
          key: 'name',
          dataIndex: 'name'
        },
        {
          title: messages('common.operation'),
          key: 'operation',
          width: '15%',
          render: (text, record) => (
            <span>
            <Popconfirm onConfirm={(e) => this.deleteItem(e, record)}
                        title={messages('setting.key1446', {controlRule: record.controlRuleName}/*你确认要删除？*/)}>
              <a href="#" onClick={(e) => {
                e.preventDefault();
                e.stopPropagation();
              }}>
                {messages('common.delete')}
              </a>
            </Popconfirm>
          </span>)
        },
      ],
    }
  }

  deleteItem = (e, record) => {
    this.setState({loading: true});
    let param = [];
    typeof record === 'undefined' ? param = this.state.selectedEntityOIDs : param.push(record.departmentDetailId);
    deptGroupService.deleteDeptGroupById(param).then(response => {
      if (typeof record !== 'undefined') {
        message.success(messages('common.delete.success', {name: record.name})); // name删除成功
      }
      this.setState({
        selectedRowKeys: [],
        selectedEntityOIDs: []
      }, this.getList());

    }).catch((e) => {
      if (e.response) {
        message.error(`${messages('common.operate.filed')},${e.response.data.message}`)
      }
    })
  };

  componentWillMount() {
    this.getList();
  }

  //查询部门组详情
  getList() {
    let params = {
      departmentGroupId: this.props.params.id,
      page: this.state.pagination.page,
      size: this.state.pagination.pageSize
    };
    deptGroupService.getDeptGroupInfo(params).then((response) => {
      if (response.status === 200) {
        response.data.map((item) => {
          item.key = item.departmentDetailId
        });
        let pagination = this.state.pagination;
        pagination.total = Number(response.headers['x-total-count']);
        this.setState({
          loading: false,
          data: response.data,
          pagination
        }, () => {
          this.refreshRowSelection()
        })
      }
    })
  }

  //控制是否弹出部门列表
  showListSelector = (flag) => {
    this.setState({
      deptListSelector: flag
    })
  };

  //点击弹框ok，保存部门
  handleListOk = (result) => {
    let param = [];
    result.result.map((item) => {
      param.push({departmentGroupId: this.props.params.id, departmentId: item.departmentId})
    });
    deptGroupService.addDept(param).then((response) => {
      if (response.status === 200) {
        this.setState({
          loading: true,
          deptListSelector: false
        }, this.getList)
      }
    });
  };

  //返回部门组
  handleBack = () => {
    this.context.router.push(menuRoute.getMenuItemByAttr('department-group', 'key').url);
  };

  //列表选择更改
  onSelectChange = (selectedRowKeys) => {
    this.setState({selectedRowKeys});
  };

  //选择一行
  //选择逻辑：每一项设置selected属性，如果为true则为选中
  //同时维护selectedEntityOIDs列表，记录已选择的OID，并每次分页、选择的时候根据该列表来刷新选择项
  onSelectRow = (record, selected) => {
    let temp = this.state.selectedEntityOIDs;
    if (selected)
      temp.push(record.departmentDetailId);
    else
      temp.delete(record.departmentDetailId);
    this.setState({
      selectedEntityOIDs: temp,
      batchDelete: temp.length > 0 ? false : true
    })
  };

  //全选
  onSelectAllRow = (selected) => {
    let temp = this.state.selectedEntityOIDs;
    if (selected) {
      this.state.data.map(item => {
        temp.addIfNotExist(item.departmentDetailId)
      })
    } else {
      this.state.data.map(item => {
        temp.delete(item.departmentDetailId)
      })
    }
    this.setState({
      selectedEntityOIDs: temp,
      batchDelete: temp.length > 0 ? false : true
    })
  };

  //换页后根据OIDs刷新选择框
  refreshRowSelection() {
    let selectedRowKeys = [];
    this.state.selectedEntityOIDs.map(selectedEntityOID => {
      this.state.data.map((item, index) => {
        if (item.departmentDetailId === selectedEntityOID)
          selectedRowKeys.push(index);
      })
    });
    this.setState({selectedRowKeys});
  }

  //清空选择框
  clearRowSelection() {
    this.setState({selectedEntityOIDs: [], selectedRowKeys: []});
  }

  //分页点击
  onChangePager = (pagination, filters, sorter) => {
    let temp = this.state.pagination;
    temp.page = pagination.current - 1;
    temp.current = pagination.current;
    temp.pageSize = pagination.pageSize;
    this.setState({
      pagination: temp
    }, () => {
      this.getList();
    })
  };

  render() {
    const {batchDelete, pagination, columns, data,
      deptSelectorItem, deptListSelector, selectedRowKeys} = this.state;

    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      onSelect: this.onSelectRow,
      onSelectAll: this.onSelectAllRow
    };

    return (
      <div className="budget-item-detail">
        <div className="table-header">
          <div className="table-header-buttons">
            <Button type="primary"
                    onClick={() => this.showListSelector(true)}>
              {messages('common.add')}</Button> {/*添加公司*/}
            <Button disabled={batchDelete}
                    onClick={this.deleteItem}>
              {messages('common.delete')}</Button>
          </div>
          <div className="table-header-title">
            {messages('common.total', {total: `${pagination.total}`})}
          </div>
          {/*共搜索到*条数据*/}
        </div>
        <ResizeTable
          dataSource={data}
          columns={columns}
          onChange={this.onChangePager}
          rowSelection={rowSelection}
          pagination={pagination}
          size="middle"
          bordered
        />
        <div style={{margin: "20px 0"}}>
          <a style={{fontSize: 14}} onClick={this.handleBack}>
            <Icon type="rollback" style={{marginRight: '5px'}}/>{messages('common.back')}
          </a>
        </div>
        <ListSelector type="company_item"
                      visible={deptListSelector}
                      onOk={this.handleListOk}
                      selectorItem={deptSelectorItem}
                      extraParams={{departmentGroupId: this.props.params.id}}
                      onCancel={() => this.showListSelector(false)}/>
      </div>)
  }
}

DepartmentGroupDetail.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {}
}

const WrappedDepartmentGroupDetail = Form.create()(DepartmentGroupDetail);

export default connect(mapStateToProps)(WrappedDepartmentGroupDetail);

